package com.mycinema.web.controller;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.junit.runner.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.HttpServerErrorException;

import com.mycinema.biz.UserBiz;
import com.mycinema.entity.User;

@Controller
public class AccountController {

	@Autowired
	private UserBiz userBiz;

	@RequestMapping("/login")
	public String login() {

		return "login";
	}

	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public String doLogin(String username, String password,
			HttpSession session,String returnUrl, Model model) {
		User user = userBiz.checkLogin(username, password);
		if (user != null) {
			// 保存session
			session.setAttribute("user", user);
			if(returnUrl !=null && !returnUrl.isEmpty()){
				return "redirect:"+returnUrl;
			}
			return "redirect:index";
		} else {
			// model.addAttribute("error","用户名或者密码不正确");
			// return "login";
			throw new RuntimeException("用户名或者密码错误");
		}
	}

//	//局部的异常处理
//	@ExceptionHandler(value = RuntimeException.class)
//	public String handException(HttpServletRequest repuest, Exception e) {
//		repuest.setAttribute("error", e);
//		return "error";
//	}

		@RequestMapping("/check")
		public void check(String username,HttpServletResponse response) throws Exception{
			int count =userBiz.checkUsername(username);
			System.out.println(count);
			PrintWriter printWriter =response.getWriter();
			//printWriter.write(count);
			printWriter.print(count);
		}
}
